Page({
  data: {
    categoryId: null,
    categoryName: '',
    articles: [],
    loading: true,
    error: null,
    pageSize: 10,
    currentPage: 1,
    total: 0,
    hasMore: true
  },

  onLoad(options) {
    const { categoryId, categoryName } = options;
    this.setData({
      categoryId,
      categoryName
    });
    this.fetchArticles();
  },

  // 获取文章列表
  fetchArticles(page = 1) {
    if (page === 1) {
      this.setData({ loading: true, error: null });
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/article/category/list',
      method: 'GET',
      data: {
        categoryId: this.data.categoryId,
        pageSize: this.data.pageSize,
        current: page
      },
      success: (res) => {
        console.log('文章列表响应：', res.data);
        if (res.data.code === 200) {
          const { total, records } = res.data.data;
          
          // 如果total为0，直接显示空状态
          if (total === 0) {
            this.setData({
              articles: [],
              total: 0,
              hasMore: false,
              loading: false
            });
            return;
          }
          
          // 处理文章数据
          const formattedArticles = records.map(article => ({
            ...article,
            createTime: this.formatDate(article.createTime),
            // 处理tags字符串，转换为数组对象
            tags: article.tags ? article.tags.split(',').map(tag => ({
              name: tag.trim(),
              color: this.getRandomColor() // 为每个标签生成随机颜色
            })) : []
          }));

          this.setData({
            articles: page === 1 ? formattedArticles : [...this.data.articles, ...formattedArticles],
            total,
            currentPage: page,
            hasMore: this.data.pageSize * page < total,
            loading: false
          });
        } else {
          this.setData({
            error: res.data.message || '获取文章列表失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取文章列表失败：', err);
        this.setData({
          error: '网络错误，请稍后重试',
          loading: false
        });
      }
    });
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 点击文章
  onArticleTap(e) {
    const article = e.currentTarget.dataset.article;
    // 跳转到文章详情页
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${article.id}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchArticles(1);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.fetchArticles(this.data.currentPage + 1);
    }
  },

  // 生成随机颜色
  getRandomColor() {
    const colors = [
      '#E8F4D9', // 浅绿
      '#FCE6E6', // 浅红
      '#E6F3FF', // 浅蓝
      '#FFF3E6', // 浅橙
      '#F3E6FF', // 浅紫
      '#E6FFF3', // 薄荷
      '#FFF6E6', // 浅黄
      '#F5F5F5'  // 浅灰
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }
});
